﻿/*code is far away from bug with the animal protecting
*  ┏┓　　　┏┓
*┏┛┻━━━┛┻┓
*┃　　　　　　　┃ 　
*┃　　　━　　　┃
*┃　┳┛　┗┳　┃
*┃　　　　　　　┃
*┃　　　┻　　　┃
*┃　　　　　　　┃
*┗━┓　　　┏━┛
*　　┃　　　┃
*　　┃　　　┃
*　　┃　　　┗━━━┓
*　　┃　神兽保佑　　┣┓
*　　┃　代码无BUG！ ┏┛
*　　┗┓┓┏━┳┓┏┛
*　　　┃┫┫　┃┫┫
*　　　┗┻┛　┗┻┛ 
*　　　
*/

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;

namespace Middleware
{
    public static class EntityHelper
    {
        public static List<T> GetEntity<T>(this DataTable tb) 
        {
            List<T> list = new List<T>();           
            foreach (DataRow dr in tb.Rows)
            {
                T t = (T)Activator.CreateInstance(typeof(T));
                var s = t.GetType().GetProperties();
                foreach(PropertyInfo info in s)
                {
                    try
                    {
                        info.SetValue(t, dr[info.Name] ?? null);
                    }
                    catch
                    {
                        info.SetValue(t, default);
                    }
                }
                list.Add(t);
            }
            return list;
        }
        public static string GetInsertSql<T>(this T t) where T:BaseEntity
        {
            var s = t.GetType().GetProperties();
            string sql = "insert into " + t.GetType().Name+"(";
            string values = " values(";
            foreach (PropertyInfo info in s)
            {
                if(info.GetValue(t)==null||info.Name.ToLower()=="id")
                {
                    continue;
                }
                sql += info.Name + ",";
                values += "'"+info.GetValue(t)+"',";
            }
            values = values.TrimEnd(',') + ")";
            sql= sql.TrimEnd(',') +")"+ values;
            return sql;
        }

        public static string GetUpdateSql<T>(this T t) where T:BaseEntity
        {
            var s = t.GetType().GetProperties();
            string sql = "update " + t.GetType().Name +"set ";
            object id=-1;
            foreach (PropertyInfo info in s)
            {
                if (info.GetValue(t) == null)
                {
                    sql = sql + info.Name + "=null,";
                }
                else
                    sql =sql+ info.Name + "='"+info.GetValue (t)+",";
                if(info.Name.ToLower()=="id")
                {
                    id=info.GetValue(t);
                }
            }
            sql = sql.TrimEnd(',')+"where Id="+id;
            return sql;
        }

        public static string GetDeleteSql<T>(this T t) where T:BaseEntity
        {
            var s = t.GetType();
            string sql = "update " + s.Name + " set isdelete=1 where id=" + s.GetProperty("Id").GetValue(t);
            return sql;
        }
    }
}
